import React,{ useRef , useEffect} from "react";
import {SERIES} from "@/utils/const.js"
import {onFn,offFn} from "@/utils/elUtils"
import PropTypes from "prop-types"

 function  FilterSeries(props) {
    const {show,change,checked}=props,
          el=useRef(null);
   let startY=0,moveY=0,moveArr=[];
   function startFn(event){
        startY=event.targetTouches[0].clientY;
        moveArr=[];
        onFn(el.current,"touchmove",moveFn);
        onFn(document,"touchend",endFn);
   } 
   function moveFn(event){
         moveY=event.targetTouches[0].clientY-startY;
         moveArr.push(Math.abs(moveY))
   }
   function endFn(event){
        offFn(el.current,"touchmove",moveFn)
        offFn(document,"touchend",endFn)
        if(!moveArr.length||Math.max.apply(Math,moveArr)<10){
            findLi(event.target)
        }
    }
    function findLi(target){
        let tagName=target.tagName;
        while (!(tagName=='LI'||tagName=='BODY')) {
            target=target.parentNode
            tagName=target.tagName
        }
        if(tagName=='LI'){
         
            change({id:target.getAttribute("data-id"),value:target.getAttribute("data-label")})
        }else{
            change()
        }  
    }
    useEffect(()=>{
        onFn(el.current,"touchstart",startFn)
        return ()=>{
            offFn(el.current,"touchstart",startFn)
        }
    })

    return (
        <div className="filter_series" ref={el}>
            <ul>
                <li data-id="" className={checked==''?'on':''} data-label="全选">全选</li>
                {
                    SERIES.map(item=> <li data-id={item.key} className={checked==item.key?'on':''} data-label={item.value} key={item.key}>{item.value}</li>  )
                }
            </ul>
        </div>
    )
}

FilterSeries.defaultProps={
    show:false,
    change:()=>{},
    checked:""
}
FilterSeries.propTypes={
    show:PropTypes.bool,
    change:PropTypes.func,
    checked:PropTypes.string
}
export default FilterSeries